sorted() function¶
Sort a given sequence¶
String, List, and Tuple
# String (based on ASCII translations)
S = 'python'
print(sorted(S)) # ['p', 'h', 'n', 'o', 't', 'y']
# List
L = ['q', 'w', 'r', 'e', 't', 'y']
print(sorted(L)) # ['e', 'q', 'r', 't', 'w', 'y']
# Vowels Tuple
T = ('q', 'w', 'r', 'e', 't', 'y')
print(sorted(T)) # ['e', 'q', 'r', 't', 'w', 'y']
Sort a given collection in descending order¶
Set, Frozen Set, and Dictionary
# Set
S = {'q', 'w', 'r', 'e', 't', 'y'}
print(sorted(S, reverse=True)) # ['y', 'w', 't', 'r', 'q', 'e']
# Frozen Set
FS = frozenset(('q', 'w', 'r', 'e', 't', 'y'))
print(sorted(FS, reverse=True)) # ['y', 'w', 't', 'r', 'q', 'e']
# Dictionary
D = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5. 'y': 6}
print(sorted(D, reverse=True)) # ['y', 'w', 't', 'r', 'q', 'e']
Sort the List having a key function¶
# take second element for sort
def takeSecond(x):
return x[1]
LOT = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
sortedList = sorted(LOT, key=takeSecond)
print('Sorted list:', sortedList) # [(4, 1), (2, 2), (1, 3), (3, 4)]
Ex: Sort based on remainder¶
# take remainder on dividing from 7
def takeRemainder(x):
return x % 7
L = [15, 3, 11, 7]
print "Normal sort :", sorted(L) # [3, 7, 11, 15]
print "Sorted with key:", sorted(L, key=takeRemainder) # [7, 15, 3, 11]
Ex: Sort based on len¶
L = ["cccc", "b", "dd", "aaa"]
print("Normal sort :", sorted(L)) # ['aaa', 'b', 'cccc', 'dd']
print("Sort with len :", sorted(L, key=len)) # ['b', 'dd', 'aaa', 'cccc']